package com.mec.web.y2012.coreservlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

public class NetworkServer {
	
	private int port, maxConnections;
	
	public NetworkServer(int port, int maxConnections) {
		super();
		this.port = port;
		this.maxConnections = maxConnections;
	}

	public void listen(){
		int i = 0;
		try{
			ServerSocket listener = new ServerSocket(port);
			Socket server;
			while((i ++ <maxConnections) ||(0 == maxConnections)){
				server = listener.accept();
				
				synchronized(this){
					i++;
				}
				
				handleConnection(server);
				
				synchronized(this){
					--i;
				}
			}
		}catch(IOException ioe){
			logger.error(ioe);
		}
	}
	
	protected void handleConnection(Socket server) throws IOException{
		BufferedReader in = SocketUtil.getReader(server);
		PrintWriter out = SocketUtil.getWriter(server);
		//
		logger.info("Generic Network Server: got connection from " +
				server.getInetAddress().getHostAddress() + 
				"\n with first line '" + in.readLine() + "')"
				);
		out.println("Generic Network Server");
		server.close();
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getMaxConnections() {
		return maxConnections;
	}

	public void setMaxConnections(int maxConnections) {
		this.maxConnections = maxConnections;
	}


	private static final Logger logger = 
			Logger.getLogger(NetworkServer.class);
}
